const { createApp, ref, reactive, onMounted } = Vue;
const { ElMessage } = ElementPlus;

// 导入 Element Plus 图标
const app = createApp({
  setup() {
    // 基础配置
    const apiBaseUrl = 'http://localhost:5000/api';
    const uploadUrl = `${apiBaseUrl}/upload`;
    const activeStep = ref(0);
    
    // 上传状态
    const uploadStatus = reactive({
      success: false,
      error: false,
      message: ''
    });
    
    // 分析状态
    const analyzeStatus = reactive({
      success: false,
      error: false,
      message: ''
    });
    
    // 数据
    const taskId = ref('');
    const fileTree = ref([]);
    const treeText = ref('');
    const modules = ref([]);
    const models = ref([]);
    const selectedModel = ref('deepseek');
    const analyzing = ref(false);
    
    // 获取AI模型列表
    const getModels = async () => {
      try {
        const response = await axios.get(`${apiBaseUrl}/models`);
        models.value = response.data;
        
        // 设置默认选择的模型
        if (models.value.length > 0) {
          selectedModel.value = models.value[0].id;
        }
      } catch (error) {
        console.error('获取模型列表失败:', error);
      }
    };
    
    // 上传前检查
    const beforeUpload = (file) => {
      const allowedTypes = [
        'application/zip', 
        'application/x-rar-compressed', 
        'application/x-7z-compressed',
        'application/x-tar',
        'application/gzip'
      ];
      
      // 检查文件类型
      const isValidType = allowedTypes.includes(file.type) || 
                          /\.(zip|rar|7z|tar|gz)$/i.test(file.name);
      
      if (!isValidType) {
        ElMessage.error('不支持的文件类型，请上传压缩文件');
        return false;
      }
      
      // 检查文件大小
      const isLessThan100M = file.size / 1024 / 1024 < 100;
      if (!isLessThan100M) {
        ElMessage.error('文件大小不能超过100MB');
        return false;
      }
      
      return true;
    };
    
    // 上传成功处理
    const handleUploadSuccess = (response) => {
      if (response.success) {
        uploadStatus.success = true;
        uploadStatus.error = false;
        taskId.value = response.task_id;
        fileTree.value = response.file_tree;
        treeText.value = response.tree_text;
        ElMessage.success('文件上传成功');
      } else {
        handleUploadError(response.error || '上传失败');
      }
    };
    
    // 上传失败处理
    const handleUploadError = (error) => {
      uploadStatus.success = false;
      uploadStatus.error = true;
      uploadStatus.message = typeof error === 'string' ? error : '上传失败，请重试';
      ElMessage.error(uploadStatus.message);
    };
    
    // 格式化文件树数据为树形结构
    const formatFileTree = (files) => {
      const tree = [];
      const map = {};
      
      files.forEach(file => {
        const parts = file.split('/');
        let currentLevel = tree;
        
        parts.forEach((part, index) => {
          // 构建当前路径
          const path = parts.slice(0, index + 1).join('/');
          
          // 检查是否已存在这个节点
          if (!map[path]) {
            const newNode = {
              label: part,
              path: path,
              children: []
            };
            
            map[path] = newNode;
            currentLevel.push(newNode);
          }
          
          // 移动到下一级
          currentLevel = map[path].children;
        });
      });
      
      return tree;
    };
    
    // 格式化模块文件列表为树形结构
    const formatModuleFiles = (files) => {
      if (!files || !Array.isArray(files)) return [];
      return formatFileTree(files);
    };
    
    // 获取文件树文本
    const getFileTreeText = async () => {
      if (!taskId.value) return;
      
      try {
        const response = await axios.get(`${apiBaseUrl}/tree?task_id=${taskId.value}`);
        if (response.data.success) {
          treeText.value = response.data.tree_text;
        }
      } catch (error) {
        console.error('获取文件树文本失败:', error);
      }
    };
    
    // 分析文件
    const analyzeFiles = async () => {
      if (!taskId.value) {
        ElMessage.error('任务ID不存在，请先上传文件');
        return;
      }
      
      analyzing.value = true;
      analyzeStatus.success = false;
      analyzeStatus.error = false;
      
      try {
        const response = await axios.post(`${apiBaseUrl}/analyze`, {
          task_id: taskId.value,
          model_id: selectedModel.value
        });
        
        if (response.data.success) {
          analyzeStatus.success = true;
          modules.value = response.data.modules || [];
          activeStep.value = 2;
          ElMessage.success('分析完成');
        } else {
          throw new Error(response.data.error || '分析失败');
        }
      } catch (error) {
        analyzeStatus.error = true;
        analyzeStatus.message = error.message || '分析失败，请重试';
        ElMessage.error(analyzeStatus.message);
      } finally {
        analyzing.value = false;
      }
    };
    
    // 下载所有合并文件
    const downloadAllFiles = () => {
      if (!taskId.value) {
        ElMessage.error('任务ID不存在');
        return;
      }
      
      window.open(`${apiBaseUrl}/download?task_id=${taskId.value}`);
    };
    
    // 下载特定模块的文件
    const downloadModuleFiles = (moduleName) => {
      if (!taskId.value || !moduleName) {
        ElMessage.error('参数错误');
        return;
      }
      
      window.open(`${apiBaseUrl}/download?task_id=${taskId.value}&module=${encodeURIComponent(moduleName)}`);
    };
    
    // 组件挂载时获取模型列表
    onMounted(() => {
      getModels();
    });
    
    return {
      apiBaseUrl,
      uploadUrl,
      activeStep,
      uploadStatus,
      analyzeStatus,
      taskId,
      fileTree,
      treeText,
      modules,
      models,
      selectedModel,
      analyzing,
      beforeUpload,
      handleUploadSuccess,
      handleUploadError,
      formatFileTree,
      formatModuleFiles,
      getFileTreeText,
      analyzeFiles,
      downloadAllFiles,
      downloadModuleFiles
    };
  }
});

// 导入Element Plus图标
app.component('upload-filled', ElementPlusIconsVue.UploadFilled);

// 挂载应用
app.use(ElementPlus);
app.mount('#app'); 